/**
 * 区划标签图层 通过marker实现  自定义divIcon
 */
import up from "../../css/regionlable/up.gif";
import down from "../../css/regionlable/down_hover.png";
import build from "../../css/regionlable/build.png";
import sgisRegionBase from "../../sfgis.region.base";
import hlLayer from "../../lib/systemlayers/hl.layer.js";
import sgisMapBase from "../../sfgis.map.base";
import regionUrl from "static/config/region.js";
import axios from 'axios';
import Layer from "@/utils/map/lib/main.js";

export default {
  regionLableLayer: null,
  /**
   * 添加区划标签到地图
   * @param {Array} datas 区划信息
   * [{ "id": "", "regioncode": "", "regionname": "", "regionlevel":"","regiontype":"","rname":"区划所在的面数据集","pname":"区划所在的点数据集","lon": "", "lat": "" } ...]
   * @param {Object} map 地图对象
   */
  createLayer(datas, map) {
    //先清除一下原有的标签
    this.cleanLables(map);
    this.addLables(datas,map);
  },
  showLayer(map) {
    //此处根据样式显示
    let className = ".region-lable-" + map._container.id;
    $(className).show();
  },
  hideLayer(map) {
    let className = ".region-lable-" + map._container.id;
    $(className).hide();
    // this.regionLableLayer.remove();
    //此处根据央视隐藏
  },
  //切换标签显隐
  toggleLayer(map){
    let className = ".region-lable-" + map._container.id;
    $(className).toggle();
  },

  cleanLables(map) {
    let className = ".region-lable-" + map._container.id;
    $(className).remove();
  },
  /**
   *
   * @param {Arrays} datas 区划数据
   * [{ "id": "", "regioncode": "", "regionname": "", "regionlevel":"","regiontype":"","rname":"","pname":"","lon": "", "lat": "" } ...]
   */
  refreshRegion(datas,map) {
    // 清除原有的区划标签
    this.cleanLables();
    // 添加新区划标签
    this.addLables(datas);
  },
  /**
   *  构造区划标签
   * @param {Array} datas 区划数据
   * [{ "id": "", "regioncode": "", "regionname": "", "regionlevel":"","regiontype":"","rname":"","pname":"","lon": "", "lat": "" } ...]
   */
  addLables(datas,map) {
    if(!datas || datas.length <=  0){
      return;
    }
    const regionLevelTmp = sgisRegionBase.regionUtils.getRegionLevel(datas[0].regioncode);
    for (let i = 0; i < datas.length; i++) {
      // 区划信息
      let dataTemp = datas[i];
      var el = document.createElement('div');
      el.className = 'region-lable-' + map._container.id;
      if(regionLevelTmp === 8){
        el.innerHTML=this.getBuildIconHtml(dataTemp,map);
      }else {
        el.innerHTML=this.getIconHtml(dataTemp,map);
      }
      new mapboxgl.Marker(el)
        .setLngLat([dataTemp.lon,dataTemp.lat])
        .addTo(map);
    }
    let _this = this;
    // 事件绑定
    $("img.labelpre").unbind("click");
    $("div.labelName").unbind("click");
    $("img.labelnext").unbind("click");
    $("img.build").unbind("click");
    if(regionLevelTmp < 8) {
      // 为下钻添加
      $("img.labelnext").bind("click", function() {
        let code = $(this).attr("code");
        // 查询下级区划代码信息(后台查询)
        let req = {
          rcId:config.regions.rcid,
          regionCode:code,
          regionCodeType:""
        }
        _this.getRegion(req,function(data){
          _this.updateMapView(data);
          EventBus.$emit("changeToolRegion", data,"upOrDownDirr"); //发送给基层查询页
        });
      });
      // 为上卷添加事件
      $("img.labelpre").bind("click", function() {
        let code = $(this).attr("code");
        const odllevel = sgisRegionBase.regionUtils.getRegionLevel(code);
        const oldparRegionCode = sgisRegionBase.regionUtils.getRegionCodeByLevel(code,odllevel);
        const level = sgisRegionBase.regionUtils.getRegionLevel(oldparRegionCode);
        const parRegionCode = sgisRegionBase.regionUtils.getRegionCodeByLevel(oldparRegionCode,level);
        let maxLevel = parseInt(sgisRegionBase.regionInfos.getMaxLevel());
        let req = {
          rcId:config.regions.rcid,
          regionCode:parRegionCode,
          regionCodeType:config.regions.regionCodeType
        }
        _this.getRegion(req,function(data){
          let dataTemp = [];
          // 如果上钻到最高层则只显示有权限的区划面
          if(maxLevel === parseInt(level)){
            dataTemp = sgisRegionBase.regionInfos.getMaxRegionINfo();
          }else {
            dataTemp = data;
          }
          _this.updateMapView(dataTemp);
          EventBus.$emit("changeToolRegion", dataTemp,"upOrDownDirr"); //发送给基层查询页
        });
      });
      // 添加lable事件
      $("div.labelName").bind("click", function() {
        // 暂时没用到
      });
    }else { // 建筑物 没有上钻下钻直接显示建筑物图标
      $("img.build").bind("click", function() {
        // 暂时没用到
        let buildcode = $(this).attr("code");
        let lat = $(this).attr("lat");
        let lon = $(this).attr("lon");
        let latlon = [lon,lat];
        EventBus.$emit("getBuildDWList",buildcode,latlon); // 报告区划标签添加完成
      });
    }

    // todo  根据区划等级判断上卷下钻按钮的显示
    EventBus.$emit("addRegionLablesComplete"); // 报告区划标签添加完成
  },
  /**
   * 自定义标签html
   * @param {Object} dataTemp 区划信息
   * { "id": "", "regioncode": "", "regionname": "", "regionlevel":"","regiontype":"","rname":"","pname":"","lon": "", "lat": "" }
   */
  getBuildIconHtml(dataTemp) {
    return (
      '<div id="' +
      dataTemp.regioncode +
      '_label" style="cursor:hand;    -webkit-border-radius: 1em!important;\n' +
      '">' +
      '<table class="cunLabel" style="border-collapse: collapse;">' +
      // '<tbody><tr style="background-color: dodgerblue;height:8px;">' +
      '<tbody><tr style="height:8px;">' +
      '<td height="20px"><img src="' +
      build +
      '" code="' +
      dataTemp.regioncode +
      '" code="' +
      '" name="' +
      (dataTemp.regionname=="空"?"未命名建筑物":dataTemp.regionname) +
      '"  level="' +
      dataTemp.regionlevel +
      '" regiontype="' +
      dataTemp.regiontype +
      '" rname="' +
      dataTemp.rname +
      '" pname="' +
      dataTemp.pname +
      '" lon="' +
      dataTemp.lon +
      '" lat="' +
      dataTemp.lat +
      '" style="height:30px;width:40px;" class="build">' +
      '</td>' +
      "</tr></tbody></table></div>"
    );
  },
  /**
   * 自定义标签html
   * @param {Object} dataTemp 区划信息
   * { "id": "", "regioncode": "", "regionname": "", "regionlevel":"","regiontype":"","rname":"","pname":"","lon": "", "lat": "" }
   */
  getIconHtml(dataTemp) {
    // 当前用户显示的最大行政区划级别
    let maxLevel = parseInt(sgisRegionBase.regionInfos.getMaxLevel());
    let level = parseInt(
      sgisRegionBase.regionUtils.getRegionLevel(dataTemp.regioncode)
    );

    // 根据区划等级显示上卷 下钻按钮
    let preDisplay = "";
    let nextDisplay = "";
    if (level <= maxLevel) {
      preDisplay = "display:none;"; // 不显示上钻
    } else if (level >= 7) {   // 四川普查小区要显示
      nextDisplay = "display:none;"; // 不显示下钻
    }
    // marker lable样式
    return (
      '<div class="region-lable-marker" id="' +
      dataTemp.regioncode +
      '_label" style="cursor:hand;    -webkit-border-radius: 1em!important;"\n' +
      '    \n' +
      '   >' +
      '<table class="cunLabel" style="border-collapse: collapse;">' +
      // '<tbody><tr style="background-color: dodgerblue;height:8px;">' +
      '<tbody><tr class="tr" style="height:8px;">' +
      '<td class="up" height="20px" style="cursor: pointer;width:20px;' +
      preDisplay+
      '"><img src="' +
      '" code="' +
      dataTemp.regioncode +
      '" name="' +
      dataTemp.regionname +
      '"  rcid="' +
      dataTemp.rcid +
      '"  level="' +
      dataTemp.regionlevel +
      '" regiontype="' +
      dataTemp.regiontype +
      '" rname="' +
      dataTemp.rname +
      '" pname="' +
      dataTemp.pname +
      '" style="height:14px;width:20px;' +
      ';" class="labelpre"></td>' +
      '<td class="regiontext" height="20px"><div class="labelName" code="' +
      dataTemp.regioncode +
      '" name="' +
      dataTemp.regionname +
      '"  level="' +
      dataTemp.regionlevel +
      '" regiontype="' +
      dataTemp.regiontype +
      '" rname="' +
      dataTemp.rname +
      '" pname="' +
      dataTemp.pname +
      '" style="font-size:14px;white-space:nowrap;position:relative;">' +
      dataTemp.regionname +
      "</div></td>" +
      '<td class="down" height="20px" style="cursor: pointer;'+nextDisplay +
      '"><img src="' +
      '" code="' +
      dataTemp.regioncode +
      '" code="' +
      '" name="' +
      dataTemp.regionname +
      '"  level="' +
      dataTemp.regionlevel +
      '" regiontype="' +
      dataTemp.regiontype +
      '" rname="' +
      dataTemp.rname +
      '" pname="' +
      dataTemp.pname +
      '" style="height:12px;width:20px;' +
      '" class="labelnext"></td>' +
      "</tr></tbody></table></div>"
    );
  },

  //获取区划树数据
  getRegion(req, callback) {
    var token_type = localStorage.getExpire("token_type");
    var access_token = localStorage.getExpire("access_token");
    let Authorization = token_type+" "+access_token;
    let that = this;
    axios.get(regionUrl.getRegionTree,{
      params: req,
      headers:{
        'Authorization':Authorization
      }
    })
      .then(function (response) {
        if(response.status == 200){
          var data = response.data.data;
          if(data.length < 1){
            alert("下级区划为空");
            return;
          }
          callback(data);
        }
      })
      .catch(function (error) {
        console.log(error);
      });

  },
  //更新地图高亮选中
  updateMapView(tagsdata){
    let viewArr = [];
    let haschild= false;//是否有下级（这里选择的是同一级别的区划）
    for(let i =0; i < tagsdata.length ; i++){
      let level = sgisRegionBase.regionUtils.getRegionLevel(tagsdata[i].code);
      let dataSetName = sgisRegionBase.regionUtils.getDataSetNameByRegionLevel(level);
      viewArr.push({
        id: tagsdata[i].code,
        regioncode: tagsdata[i].code,
        regionname: tagsdata[i].name,
        regiontype: "1", // 1普通区划 2高新区 3特色区
        regionlevel: level,
        lat: "",
        lon: "",
        rname: dataSetName,
        pname: dataSetName
      });
    }
    Layer.hlLayer.addHLBoundary(viewArr, "1", sgisMapBase.getMap(), haschild);
  },
};
